<template>
	<div class="template">
		<el-form :model="loginForm" status-icon :rules="rules2" ref="loginForm" label-width="100px" class="demo-ruleForm">
			<el-form-item label="账户" prop="phone"><el-input type="text" v-model="loginForm.phone" auto-complete="off"></el-input></el-form-item>
			<el-form-item label="密码" prop="password"><el-input type="password" v-model="loginForm.password" auto-complete="off"></el-input></el-form-item>
			<el-button :loading="loading" type="primary" style="width:100%;margin-bottom:30px;" @click.native.prevent="handleLogin">Login</el-button>
		</el-form>
	</div>
</template>
<script>
export default {
	data() {
		return {
			loginForm: {
				phone: '',
				password: ''
			},
			rules2: {
				phone: [{ required: true, message: '请输入账户', trigger: 'blur' }],
				password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
			},
			loading: false,
			redirect: undefined,
			otherQuery: {}
		};
	},
	watch: {
	  $route: {
	    handler: function(route) {
	      const query = route.query
	      if (query) {
	        this.redirect = query.redirect
	        this.otherQuery = this.getOtherQuery(query)
	      }
	    },
	    immediate: true
	  }
	},
	created() {},
	mounted() {},
	methods: {
		handleLogin(formName) {
			this.$refs.loginForm.validate(valid => {
				if (valid) {
					this.loading = true;
					this.$store
						.dispatch('getToken/login', this.loginForm)
						.then(() => {
							this.$router.push({ path: this.redirect || '/', query: this.otherQuery });
							this.loading = false;
						})
						.catch(() => {
							this.loading = false;
						});
				} else {
					return false;
				}
			});
		},
		getOtherQuery(query) {
		  return Object.keys(query).reduce((acc, cur) => {
		    if (cur !== 'redirect') {
		      acc[cur] = query[cur]
		    }
		    return acc
		  }, {})
		}
	}
};
</script>

<style scoped></style>
